#!/usr/bin/env bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export CI_COMMIT_REF_NAME=$(echo ${CI_COMMIT_REF_NAME} | sed 's/\//./g')
export IMAGE_NAME=${PROJECT_TYPE}-${TEAM}-${PROJECT_NAME}
export IMAGE_VERSION=${CI_COMMIT_REF_NAME}-${CI_PIPELINE_ID}

echo "Runner Path: ${PATH}"
echo "Private DTR Url: ${PRIVATE_DTR_URL}"
echo "Start build image:" $(date)

export BASE_URL=$BaseUrl
export RELEASE_VERSION=$IMAGE_VERSION
export ASSET_PUBLIC_PATH=/$BaseUrl/
export RELEASE_BRANCH=release
export COMMIT_HASH=$COMMIT_HASH
export PIPELINE=$PIPELINE
export REF_NAME=$REF_NAME

yarn config set cache-folder /app/.yarn_caches
CYPRESS_INSTALL_BINARY=0 yarn install --ignore-engines
yarn run build

if [ ! -z ${IN_HOUSE} ];then
    TEAM=internal
fi

cp ./Dockerfile ./dist
cp ./nginx.conf ./dist
cp ./init.sh ./dist

cd ./dist
mkdir -p monitor/health && echo pang > monitor/health/index.html

if [ $COMMIT_TAG ]; then
    IMAGE_VERSION=${COMMIT_TAG}
fi

IMAGE=${PRIVATE_DTR_URL}/${TEAM}/${IMAGE_NAME}:${IMAGE_VERSION}
echo "Image path: ${IMAGE}"

if [[ $AWS_DTR_URL != *local-dtr.zhihuiya.com* ]]; then
    sed -i "s/local-dtr.zhihuiya.com\/base/${PRIVATE_DTR_URL}\/ops-basic/g" Dockerfile
fi

docker build -t $IMAGE ./
docker push $IMAGE

cd ..
